library(tseries)
library(RToolbox)
yahooSeriesName <- "smic.sw"
yahooSeriesName <- "^ssmi"


rawData <- get.hist.quote(yahooSeriesName,quote="AdjClose",compression="m")

Date <- attributes(rawData)$index

rawDataNumeric <- as.numeric(rawData)

ret <- logReturn(rawDataNumeric)
ret2 <- simpleReturn(rawDataNumeric)

eqData <- data.frame(Date=Date,PRICE=rawDataNumeric)

eqData[,"logReturn"] <- c(NA,logReturn(eqData[,"PRICE"]))

lag1 <- 6
eqData[,"lagSD1"] <- c(rep(NA,lag1-1),rollingApply(eqData[,"logReturn"],lag1,sd))
lag2 <- 36
eqData[,"lagSD2"] <- c(rep(NA,lag2-1),rollingApply(eqData[,"logReturn"],lag2,sd))
eqData[,"lagDiff"] <- eqData[,"lagSD2"] - eqData[,"lagSD1"]
eqData[,"ls"] <- c(NA,sign(eqData[1:(dim(eqData)[1]-1),"lagDiff"]))
eqData[,"finalRet"] <- eqData[,"logReturn"] * eqData[,"ls"]
eqData[,"finalSeries"] <- rep(NA,dim(eqData)[1])
eqData[(max(which(is.na(eqData$finalRet)))):dim(eqData)[1],"finalSeries"] <- exp(c(0,cumsum(eqData[!is.na(eqData$finalRet),"finalRet"])))
lagAR <- 24
eqData[,"arX"] <- c(rep(NA,lagAR-1),rollingApply(eqData[,"PRICE"],lagAR,function(x)predict(ar(x))$pred))
eqData[,"arLS"] <- c(NA,sign(eqData[1:(dim(eqData)[1]-1),"PRICE"]-eqData[1:(dim(eqData)[1]-1),"arX"]))
eqData[,"finalRetAR"] <- eqData[,"logReturn"] * eqData[,"arLS"]
eqData[,"finalSeriesAR"] <- rep(NA,dim(eqData)[1])
eqData[(max(which(is.na(eqData$finalRetAR)))):dim(eqData)[1],"finalSeriesAR"] <- exp(c(0,cumsum(eqData[!is.na(eqData$finalRetAR),"finalRetAR"])))



par(mfrow=c(3,1))
plot(eqData$Date,eqData$PRICE,typ="l")
plot(eqData$Date,eqData$finalSeriesAR,typ="l")
plot(eqData$Date,eqData$lagSD1,typ="l",ylim=c(min(eqData$lagDiff,na.rm=TRUE),max(eqData$lagSD2,na.rm=TRUE)))
lines(eqData$Date,eqData$lagSD2,col=2)
lines(eqData$Date,eqData$lagDiff,col=2,lwd=2)
abline(h=0)



plot(eqData$Date,eqData$PRICE,typ="l")
lines(eqData$Date,eqData$arX,col=2)


